package uk.ac.ebi.literature.orcid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.log4j.Logger;

import uk.ac.ebi.literature.utils.file.CsvUtils;

public class FillOrcid {
    private static Logger logger = Logger.getLogger(FillOrcid.class);

    public static void main(String[] args) throws Exception {
        String msg;
        String sapCsvFile = "C:/tmp/all_staff-23-10-13_from_jo.csv";
        String orcidCsvFile = "C:/tmp/created_orcid.csv";
        String sapOrcidCsvFile = "C:/tmp/all_staff-23-10-13_with_orcids.csv";

        // Get SAP map from sapCsvFile
        HashMap<String, ArrayList<String>> sapMap = CsvUtils.parseCsvToMap(sapCsvFile, 3);
        if (sapMap == null) {
            logger.warn("sapMap null");
            return;
        }
        
        // Get ORCID map from orcidCsvFile
        HashMap<String, ArrayList<String>> orcidMap = CsvUtils.parseCsvToMap(orcidCsvFile, 2);
        if (orcidMap == null) {
            logger.warn("orcidMap null");
            return;
        }
        
        // Fill the SAP map with ORCID
        Set<Entry<String, ArrayList<String>>> sapEntries = sapMap.entrySet();
        for (Entry<String, ArrayList<String>> sapEntry: sapEntries) {
            String email = sapEntry.getKey();
            if (orcidMap.containsKey(email)) {
                ArrayList<String> orcidRecord = orcidMap.get(email);
                String orcid = orcidRecord.get(3);
                
                ArrayList<String> sapRecord = sapEntry.getValue();
                if (sapRecord.size() == 4) {
                    sapRecord.add(orcid);
                } else if (sapRecord.size() == 5) {
                    sapRecord.set(4, orcid);
                }
            }
        }
        
        if (!CsvUtils.writeToCsv(sapOrcidCsvFile, sapMap.values())) {
            logger.error("Error in writing to CSV");
            return;
        }
        
        msg = "Succeed in writing to CSV: " + sapOrcidCsvFile;
        logger.info(msg);
        System.out.println(msg);
    }

}
